import type { StockPrice } from "./types";

const base = import.meta.env.VITE_API_BASE_URL || "";

export async function getHealth() {
  const r = await fetch(`${base}/api/health`);
  return r.json();
}

export async function getPrice(symbol: string): Promise<{ data: StockPrice }> {
  const r = await fetch(`${base}/api/stocks/${encodeURIComponent(symbol)}/price`);
  if (!r.ok) throw new Error("Failed to fetch price");
  return r.json();
}

export function connectWs(onMessage: (data: any) => void) {
  const url = (import.meta.env.VITE_WS_URL || "ws://localhost:3000") + "/ws";
  const ws = new WebSocket(url);
  ws.onopen = () => {
    // 默认订阅AAPL
    ws.send(JSON.stringify({ symbol: "AAPL" }));
  };
  ws.onmessage = (e) => {
    try {
      const data = JSON.parse(e.data);
      onMessage(data);
    } catch {}
  };
  return ws;
}